import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { asyncRouterMap, constantRouterMap } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  routes: constantRouterMap,
  addRoutes: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = state.roles.concat(roles);
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ROUTERS:(state, routers) => {
    state.addRoutes = routers
    state.routes = constantRoutes.concat(routers)
  }
}

const getters = {
  token: (state) => {
    return state.token
  },
  name: (state) => {
    return state.name
  },
  avatar: (state) => {
    return state.avatar
  },
  roles: (state) => {
    return state.roles
} 
}

const actions = {
  // user login 第一个login是$store中的方法，第二个login方法是，api里的login方法，用来调用接口的  调用login接口拿到token
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { name, avatar, roles, asyncRouterMap} = data

        // 遍历后台传来的路由字符串，转换为组件对象
        //filterAsyncRouter(routers)
        localStorage.setItem('routerCache',JSON.stringify(asyncRouterMap))
        
        //const menus = routers
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLES', roles)
        //dispatch('SET_ROUTERS', asyncRouterMap)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  
 
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')//清空用户名
        removeToken()
        resetRouter()//重置路由
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()//清除cookies中的token
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

